<template>
  <div class="home">
    <header>
      <div class="head-left">
        <img src="../assets/imagetow/time.png">
        <span>{{ HourMiniterSeconds }}</span>
      </div>
      <div class="head-right">
        <span>{{ YearMonthDay}}  </span>   |   <span>{{ weekDay}}</span>
      </div>
    </header>
    <main>
      <div class="main-head disfse " >
        <div :class="selectgroupindex==index? 'main-head-box cur': 'main-head-box' " v-for="(group, index) in groupedItems" :key="index" @click="selectgroup(group,index)" >
          <div class="head-box">
          {{ (index * 5 + 1) }} - {{ Math.min((index + 1) * 5, cabinetoptions.length) }}
          </div>
          <img v-if="selectgroupindex==index" class="fou" src="../assets/imagetow/xuanzhong.png">
        </div>
      </div>
      <div class="main-cont disfse">
        <div class="cont-item" v-for="(item, indexn) in boxdata" :key="indexn">
          <div class="item-yua">
           {{item.code}}
          </div>
          <div class="item-box">
            <span class="item-box-mi">{{item.password}}</span>
            <div v-if="item.product!==null" class="show-state">
              <div style="display: flex; gap: 10px;">

            <div  v-for="(itema,indexa) in item.product" :key="indexa" >
            <span  style="background-color:#00FF00;"  v-if="itema.outboundFlag == '1' ">{{indexa+1}}</span>
            <span  style="background-color: #FF0000 ;"  v-else>{{indexa+1}}</span>
            </div>
             </div>
            </div>
          </div>
          <img src="../assets/imagetow/kaiqi.png"  @click="selectgo(item)" alt="">
        </div>
      </div>
    </main>
  </div>
</template>

<script>

import {cabinetlist } from "@/api/archive/cabinet";
import {addTask} from "@/api/system/task";

export default {
  name: "Index",
  data() {
    return {
     YearMonthDay: '',//年月日数据
      HourMiniterSeconds:'',//时分秒数据
      selectgroupindex: 0,
      ws: "",
      queryParams: {
        wareHouseCode: "1",
      },
      cabinetoptions:[],
      boxdata:[],
      form:{
        sid:''
      },
      cabintdata:[]
    };
  },
  computed: {
    weekDay() {
      let days = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      let today = new Date();
      let weekday = today.getDay();
      return days[weekday];
    },
       groupedItems() {
      const result = [];
      for (let i = 0; i < this.cabinetoptions.length; i += 5) {
        result.push(this.cabinetoptions.slice(i, i + 5));
      }
      return result;
    }
  },
  
  created() {
    this.url=window.system.wsurl
   this.getproduct();
   setTimeout(() => {
      this.createWebSocket()
   }, 500);
  
  },
  mounted() {
 
   
        setInterval(() => {
      //年月日
      this.getYearMonthDay();
      //时分秒
      this.currentDate();
    }, 1000);
  
  },
  methods: {
    cancle() {
      this.taskshow = false;
    },

    goTarget(href) {
      window.open(href, "_blank");
    },
    selectgroup(group,index) {
      this.selectgroupindex = index;
      this.boxdata=group;
    },
  //获取年月日的方法
    getYearMonthDay() {
      const today = new Date();
      // 获取当前时间(today)的年份
      const year = today.getFullYear();
      // 获取月份
      const month = String(today.getMonth() + 1).padStart(2, "0");
      // 获取当前日
      const day = String(today.getDate()).padStart(2, "0");
      // 得到年月日
      this.YearMonthDay = `${year}-${month}-${day}`; //打印当前日期
    },
    //获取时分秒的方法
    currentDate() {
      var d = new Date();
      var year = d.getFullYear();
      var month = d.getMonth();
      month = month + 1 > 12 ? 1 : month + 1;
      month = month > 9 ? month : "0" + month.toString();
      var day = d.getDate();
      var hour = d.getHours();
      hour = hour > 9 ? hour : "0" + hour.toString();
      var minute = d.getMinutes();
      minute = minute > 9 ? minute : "0" + minute.toString();
      var second = d.getSeconds();
      second = second > 9 ? second : "0" + second.toString();
      this.HourMiniterSeconds = `${hour}:${minute}:${second}`;
    },
    //获取柜子
    getproduct() {
       cabinetlist(this.queryParams).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          response.data[i].password = '' 
        }
        this.cabinetoptions = response.data;
         console.log(this.groupedItems);
        this.selectgroup(this.groupedItems[0],0);
        
    })
    },


    selectgo(item) {
      this.form.sid=item.code;
        addTask(this.form).then((response) => {
          console.log(response)
               this.$modal
        .confirm('动态密码为：'+response.msg+'，请妥善保管！', '提示')
        .then(function () {
          
        })
        .catch(() => {});
           
        });
    },

    slectrow(row) {
      this.printdata = [];
      this.printdata.push(row);
    },
    cancelprint() {
      this.printoopen = false;
    },

    printshow() {
      this.printoopen = true;
    },
    createWebSocket() {
      try {
        if ("WebSocket" in window) {
          this.ws = new WebSocket(this.url);
        } else if ("MozWebSocket" in window) {
          this.ws = new MozWebSocket(this.url);
        } else {
          alert("No Support WebSocket!");
          return;
        }

        this.initEventHandle();
      } catch (e) {
        this.reconnect(this.url);
        console.log(e);
      }
    },

    initEventHandle() {
      var self = this;

      var heartCheck = {
        timeout: 50000, //50s发一次心跳
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
          clearTimeout(heartCheck.timeoutObj);
          clearTimeout(heartCheck.serverTimeoutObj);
          return heartCheck;
        },
        start: function () {
          console.log(self);
          var that = this;
          heartCheck.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常

            self.ws.send("ping");
            console.log("ping!");
            heartCheck.serverTimeoutObj = setTimeout(function () {
              //如果超过一定时间还没重置，说明后端主动断开了
              self.ws.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, heartCheck.timeout);
          }, heartCheck.timeout);
        },
      };
      self.ws.onclose = function () {
        self.reconnect(self.url);
        console.log("llws connection close!" + new Date().toUTCString());
      };
      self.ws.onerror = function () {
        self.reconnect(self.url);
        console.log("llws connection error!");
      };
      self.ws.onopen = function () {
        console.log(heartCheck);
        heartCheck.reset(); //心跳检测重置
        heartCheck.start();
        console.log("llws connection successful!" + new Date().toUTCString());
      };
      self.ws.onmessage = function (event) {
        //如果获取到消息，心跳检测重置
        heartCheck.reset();
        heartCheck.start(); //拿到任何消息都说明当前连接是正常的
        console.log("llws receive message:" + event.data);
        // let msg = JSON.parse(event.data);
        // console.log( event.data)
        if (event.data !== "pong") {
             const cabintdata=JSON.parse(event.data)
          if(cabintdata.dypass!==undefined){
            if(cabintdata.dypass.length>0){
          self.cabinetoptions.forEach((item, index) => {
          cabintdata.dypass.forEach((item1, index1) => {
            if (item.code === item1.sid) {
              item.password = item1.dyPass;
            } else {
              item.password ='';
            }
          })
          })
        }else{
          self.cabinetoptions.forEach((item, index) => {
            item.password ='';
          })
        }
          }
          console.log(self.cabinetoptions)

        if(cabintdata.keyState!==undefined){
          
           if(cabintdata.keyState.length>0){
        
          console.log(self.cabinetoptions)
           console.log(cabintdata.keyState)
          self.cabinetoptions.forEach((item, index) => {
          cabintdata.keyState.forEach((item1, index1) => {
            if (item.code === item1.cabinetCode) {
              if(item.product.length>0){
                 for(let i=0;i<item.product.length;i++){
                if(item.product[i].id===item1.id){
                  item.product[i].outboundFlag=item1.outboundFlag
                }
              }
              }
             

              
              }
            })
          })
        }
        }
        
      }
      };
    },

    // window.onbeforeunload = function() {
    //   ws.close();
    // },
    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      setTimeout(function () {
        //没连接上会一直重连，设置延迟避免请求过多
        that.createWebSocket();
        that.lockReconnect = false;
      }, 2000);
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  height: 100vh;
  background: url("../assets/imagetow/bg.png") no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  padding: 30px 10% 40px 10%;
  overflow: hidden;
  position: relative;
  color: #ffffff;
  ul,
  li {
    padding: 0;
    margin: 0;
    list-style-type: none;
  }
  p {
    margin: 0;
  }

  header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #A8C4DD;
    font-size: 12px;
    font-weight: 700;
    margin-top: 1%;
    .head-left{
      img{
        width: 13px;
        height: 13px;
        vertical-align: bottom;
        margin-right: 10px;
      }
    }
  }
  main{
    margin: 5% 0 20px;
    height: 100%;
    .main-head{
      .main-head-box{
        text-align: center;
        margin: 0 14px;
        height: 88px;
        cursor: pointer;
        .head-box{
          width: 126px;
          height: 34px;
          line-height: 34px;
          text-align: center;
          background: url("../assets/imagetow/guiwxz.png") no-repeat;
          background-size: 100% 100%;
          color: #ffffff;
          font-size: 15px;
          font-weight: 700;
        }
        img{
          width: 50px;
          height: 50px;
        }
        &:hover .head-box{
          background: url("../assets/imagetow/guixz.png") no-repeat;
          background-size: 100% 100%;
        }
      }
      .main-head-box.cur{
        .head-box{
          background: url("../assets/imagetow/guixz.png") no-repeat;
          background-size: 100% 100%;
        }
      }
       
    }
    .main-cont{
      margin: 2% 15px 0;
      text-align: center;
      height: 100%;
      .cont-item{
        margin: 0 auto;
        height: 100%;
        // width: 100%;
        .item-yua{
          width: 45px;
          height: 45px;
          line-height: 45px;
          font-size: 15px;
          font-weight: 700;
          background: url("../assets/imagetow/title.png") no-repeat;
          background-size: 100% 100%;
          margin: auto;
        }
        .item-box{
          background: url("../assets/imagetow/bg2.png") no-repeat;
          background-size: 100% 100%;
          width: 205px;
          height: 55%;
          position: relative;
          .item-box-mi{
            width: 66px;
            position: absolute;
            top: 54%;
            left: calc(100% - 135px);
            z-index: 1;
            font-size: 15px;
            font-weight: 700;
          }  
          .show-state{
              position: absolute;
            top: 72%;
            left: calc(100% - 135px);
             span{
              display: inline-block;
            width: 28px;
            height: 28px;
            z-index: 1;
            font-size: 22px;
             text-align: center;
            font-weight: 700;
            border-radius:50%;
          }
         
          }


         
        }
        img{
          width: 150px;
          height: 70px;
          cursor: pointer;
        }
      }
      

    }
    
  }
  
}
.disfse {
  display: flex;
  align-items: center;
  justify-content: center;
}

</style>
